package cn.edu.gdmec.android.criminalintent;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import org.json.JSONException;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Jack on 2017/10/27.
 */

public class CrimeFragment extends Fragment {
    private static final String ARG_CRIME_ID = "crime_id";
    private static final String DIALOG_DATE = "DialogDate";

    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_CONTACT = 1;
    //使用相机
    private static final int REQUEST_PHOTO = 2;

    private Crime mCrime;
    //获取图片文件位置
    private File mPhotoFile;

    private EditText mTitleField;
    private Button mDataButton;
    private CheckBox mSolvedCheckBox;
    private Button mSuspectButton;

    private ImageButton mPhotoButton;
    private ImageView mPhotoView;

    private Callbacks mCallbacks;
    private Button mReportButton;

    public interface Callbacks{
        void onCrimeUpdated(Crime crime);
    }
    public static CrimeFragment newInstance(UUID crimeId){
        Bundle args = new Bundle (  );
        args.putSerializable ( ARG_CRIME_ID, crimeId );
        CrimeFragment fragment = new CrimeFragment ();
        fragment.setArguments ( args );
        return fragment;
    }

    @Override
    public void onAttach(Activity activity){
        super.onAttach ( activity );
        mCallbacks = (CrimeFragment.Callbacks ) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate ( savedInstanceState );
        //mCrime = new Crime ();
//        UUID crimeId = (UUID) getActivity ().getIntent ()
//                .getSerializableExtra ( CrimeActivity.EXTRA_CRIME_ID );
        UUID crimeId = (UUID ) getArguments ().getSerializable ( ARG_CRIME_ID );
        mCrime = CrimeLab.get ( getActivity () ).getCrime ( crimeId );
        //获取图片文件位置
        mPhotoFile = CrimeLab.get ( getActivity () ).getPhotoFile ( mCrime );
        //mPhotoButton = CrimeLab.get ( getActivity () ).getPhotoButton ( mCrime );
        //获得拍照
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy ( builder.build () );
        builder.detectFileUriExposure ();
    }
    @Override
    public void onPause(){
        super.onPause ();
        CrimeLab.get ( getActivity () )
                .updateCrime ( mCrime );
    }
    @Override
    public void onDetach(){
        super.onDetach ();
        mCallbacks = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){
        View v = inflater.inflate ( R.layout.fragment_crime, container, false );

        mTitleField = (EditText)v.findViewById ( R.id.crime_title );
        mTitleField.setText ( mCrime.getTitle () );
        mTitleField.addTextChangedListener ( new TextWatcher () {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCrime.setTitle ( s.toString () );
                updateCrime ();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        } );
        mDataButton = (Button)v.findViewById ( R.id.crime_date );
        updateDate ();
//        mDataButton.setEnabled ( false );
        mDataButton.setOnClickListener ( new View.OnClickListener (){
            @Override
            public void onClick(View v){
                FragmentManager manager = getFragmentManager ();
                //DatePickerFragment dialog = new DatePickerFragment ();
                DatePickerFragment dialog = DatePickerFragment.newInstance ( mCrime.getDate () );

                dialog.setTargetFragment ( CrimeFragment.this, REQUEST_DATE );
                dialog.show(manager, DIALOG_DATE);
            }
        } );

        mSolvedCheckBox = (CheckBox)v.findViewById ( R.id.crime_solved );
        mSolvedCheckBox.setChecked ( mCrime.isSolved () );
        mSolvedCheckBox.setOnCheckedChangeListener ( new CompoundButton.OnCheckedChangeListener (){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
                mCrime.setSolved ( isChecked );
                //294
                updateCrime ();
            }
        } );
        mReportButton = (Button) v.findViewById ( R.id.crime_report );
        mReportButton.setOnClickListener ( new View.OnClickListener (){
            public void onClick(View v){
                Intent i = new Intent ( Intent.ACTION_SEND );
                i.setType ( "text/plain" );
                i.putExtra ( Intent.EXTRA_TEXT, getCrimeReport () );
                i.putExtra ( Intent.EXTRA_SUBJECT,
                        getString ( R.string.crime_report_subject ));
                //选择器
                i = Intent.createChooser ( i, getString ( R.string.send_report ) );
                startActivity ( i );
            }
        } );

        //260
        final Intent pickContact = new Intent ( Intent.ACTION_PICK,
                ContactsContract.Contacts.CONTENT_URI);
        //pickContact.addCategory ( Intent.CATEGORY_HOME );
        mSuspectButton = (Button) v.findViewById ( R.id.crime_suspect );
        mSuspectButton.setOnClickListener ( new View.OnClickListener (){
            public void onClick(View v){
                startActivityForResult ( pickContact, REQUEST_CONTACT );
            }
        } );
        if (mCrime.getSuspect () != null){
            mSuspectButton.setText ( mCrime.getSuspect () );
        }

        PackageManager packageManager = getActivity ().getPackageManager ();
        if (packageManager.resolveActivity ( pickContact,
                PackageManager.MATCH_DEFAULT_ONLY) == null){
            mSuspectButton.setEnabled ( false );
        }

        mPhotoButton = (ImageButton ) v.findViewById ( R.id.crime_camera );
        //拍照和显示照片
        final Intent captureImage = new Intent ( MediaStore.ACTION_IMAGE_CAPTURE );
        boolean canTakePhoto = mPhotoFile != null &&
                captureImage.resolveActivity ( packageManager ) != null;
        mPhotoButton.setEnabled ( canTakePhoto );

        if (canTakePhoto){
            Uri uri = Uri.fromFile ( mPhotoFile );
            captureImage.putExtra ( MediaStore.EXTRA_OUTPUT, uri );
        }

        mPhotoButton.setOnClickListener ( new View.OnClickListener (){
            @Override
            public void onClick(View v){
                startActivityForResult ( captureImage, REQUEST_PHOTO );
            }
        } );

        mPhotoView = (ImageView ) v.findViewById ( R.id.crime_photo );

        //调用277
        updatePhotoView ();
        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if (resultCode != Activity.RESULT_OK){
            return;
        }

        if (requestCode == REQUEST_DATE) {
            Date date=( Date ) data
                    .getSerializableExtra ( DatePickerFragment.EXTRA_DATE );
            mCrime.setDate ( date );
            //294
            updateCrime ();
            updateDate ();
        }else if (requestCode == REQUEST_CONTACT && data != null){
            Uri contactUri = data.getData ();
            String[] queryFields = new String[]{
                    ContactsContract.Contacts.DISPLAY_NAME
            };
            Cursor c = getActivity ().getContentResolver ()
                    .query ( contactUri, queryFields, null, null, null );
            try {
                if (c.getCount () == 0){
                    return;
                }
                c.moveToFirst ();
                String suspect = c.getString ( 0 );
                mCrime.setSuspect ( suspect );
                //294
                updateCrime ();
                mSuspectButton.setText ( suspect );
            }finally {
                c.close ();
            }
            //调用
        }else if (requestCode == REQUEST_PHOTO){
            updateCrime ();
            updatePhotoView ();
        }
    }

    private void updateCrime(){
        CrimeLab.get ( getActivity () ).updateCrime ( mCrime );
        mCallbacks.onCrimeUpdated(mCrime);
    }
    private void updateDate() {
        mDataButton.setText ( mCrime.getDate ().toString () );
    }
    private String getCrimeReport(){
        String solvedString = null;
        if (mCrime.isSolved ()){
            solvedString = getString ( R.string.crime_report_solved );
        }else {
            solvedString = getString ( R.string.crime_report_unsolved );
        }
        String dateFormat = "EEE, MMM dd";
        String dateString =DateFormat.format ( dateFormat, mCrime.getDate () ).toString ();

        String suspect = mCrime.getSuspect ();
        if (suspect == null){
            suspect = getString ( R.string.crime_report_no_suspect );
        }else{
            suspect = getString ( R.string.crime_report_suspect, suspect );
        }
        String report = getString ( R.string.crime_report,
                mCrime.getTitle (), dateString, solvedString, suspect);
        return report;
    }

    private void updatePhotoView(){
        if (mPhotoFile == null || !mPhotoFile.exists ()){
            mPhotoView.setImageDrawable ( null );
        }else{
            Bitmap bitmap = PictureUtils.getScaledBitmap ( mPhotoFile.getPath (), getActivity () );
            mPhotoView.setImageBitmap ( bitmap );
        }
    }
}

